<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <!--1.2 文章铺设列表 复用组件-->
    <!-- 1.3往下滑动加载数据
      page：1页数，不传默认为1 -->
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :offset="50"
        :immediate-check="false"
        @load="onLoad"
      >
        <ArticleItem
          v-for="item in articleList"
          :key="item.art_id"
          :obj="item"
          @click.native="$router.push(`/articledetail?aid=${item.art_id}`)"
          :showX='false'
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import { timeAgo } from '../../utils/date'
import ArticleItem from '../Home/components/ArticleItem.vue'
import { searchResultListAPI } from '../../api'
export default {
  name: 'SearchResult',
  components: { ArticleItem },
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      page: 1 // 页码
    }
  },
  created () {
    this.getArticleList()
  },
  methods: {
    // 封装接口方便多次利用
    // 1.$route 当前路由对象 对象中提供了当前页面路由的所有参数
    // $router 路由的实列 里面提供了路由方法,路由钩子,完整的路由表,currnetRoute
    // --当前页面的路由对象
    // $router中的currnetRoute相当于$route
    async getArticleList () {
      const res = await searchResultListAPI({
        q: this.$route.params.keywords,
        page: this.page
      })
      this.articleList = res.data.data.results
      res.data.data.results.forEach((item) => {
        item.pubdate = timeAgo(item.pubdate)
      })
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false
      }
    },
    onLoad () {
      // 每触发一次都让页码+1去重新请求数据
      if (this.articleList.length > 0) {
        this.page++
        this.getArticleList()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
